package com.zhi.timingTask;

import com.zhi.config.Constant;
import com.zhi.entity.ALeave;
import com.zhi.entity.Student;
import com.zhi.entity.Teacher;
import com.zhi.service.LeaveService;
import com.zhi.service.MailService;
import com.zhi.service.StudentService;
import com.zhi.service.TeacherService;
import com.zhi.util.LogUtil;
import com.zhi.util.PubFun;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import java.sql.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 定时器任务
 * Configuration 1、主要用于标记配置类，兼备Component的效果
 * EnableScheduling 2、开启定时任务
 */
@Configuration
@EnableScheduling
public class ScheduleTask {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    LeaveService leaveService;

    @Autowired
    StudentService studentService;

    @Autowired
    TeacherService teacherService;

    @Autowired
    MailService mailService;

    //邮件模板
    @Value("${email.template04}")
    String emailTemplate04;

    @Value("${email.template05}")
    String emailTemplate05;


    //3.添加定时任务

    //方式1
    /*@Scheduled(fixedRate = 5000)
    private void configureTasks1(){
        System.out.println("configureTasks1");
    }*/

    //方式2
    /**
     * Cron表达式参数分别表示：
     * 注解Scheduled(cron = "0/5 * * * * ?")
     * 秒（0~59） 例如0/5表示每5秒
     * 分（0~59）
     * 时（0~23）
     * 日（0~31）的某天，需计算
     * 月（0~11）
     * 周几（ 可填1-7 或 SUN/MON/TUE/WED/THU/FRI/SAT）
     */
    @Scheduled(cron = "0 0 */1 * * ?")
    private void overdueLapse(){
        logger.info("开始扫描超期未处理的请假任务");
        Date currentDate = new Date(System.currentTimeMillis());
        Integer count = 0;

        //1、先查找所有状态为0-申请中的请假单
        ALeave al = new ALeave();
        al.setState(Constant.LEAVE_STATE_APPLY);
        List<ALeave> leaves = leaveService.findAll(al);

        //2、用请假单的开始日期与当前日期比较
        for(ALeave leave : leaves){
            Date startDate = leave.getStartDate();
            //若请假日期不晚于当前日期，即请假日期早于或等于当前日期，即超期失效
            if(!startDate.after(currentDate)){

                count++;

                //3、置为超期状态
                leave.setState(Constant.LEAVE_STATE_FAILURE);
                leaveService.edit(leave);

                //4、发邮件
                Student student = studentService.getOne(leave.getStudentId());
                Teacher teacher = teacherService.getOne(student.getGrade().getInstructor());
                String title = Constant.EMAIL_TITLE;

                //4.1、发送学生
                Map<String,String> params = new HashMap<>();
                params.put("instructorName",teacher.getName());
                params.put("studentName",student.getName());
                params.put("reason",leave.getReason());
                params.put("startDate",PubFun.getString(leave.getStartDate()));
                params.put("endDate",PubFun.getString(leave.getEndDate()));
                params.put("applyDate",PubFun.getString(leave.getApplyDate()));

                String content = PubFun.getEmailContent(emailTemplate04,params);
                logger.info("超期发学生",content);
                mailService.sendMail(title,content,student.getEmail());

                //4.2、发送指导员提醒
                String content2 = PubFun.getEmailContent(emailTemplate05,params);
                logger.info("超期发指导员",content2);
                mailService.sendMail(title,content2,teacher.getEmail());

            }
        }

        logger.info("本次超期未处理任务扫描结束，处理任务数："+count);
        LogUtil.insert("OverdueLapse","schedule","本次超期失效定时任务处理结束，处理任务数："+count);

    }

}
